package thoven.achievement.net.ideapluginachievement.ui

import com.intellij.openapi.options.Configurable
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.JBColor
import com.intellij.ui.components.*
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import thoven.achievement.net.ideapluginachievement.service.SettingsService  
import java.awt.*
import javax.swing.*

/**
 * 插件设置配置页面
 */
class SettingsConfigurable : Configurable {
    
    private val settingsService = SettingsService.getInstance()
    private var settingsPanel: JPanel? = null
    
    // 通知设置组件
    private val enableNotificationsCheckBox = JBCheckBox("启用成就通知")
    private val enableSoundCheckBox = JBCheckBox("声音提醒")
    private val enableStatusBarCheckBox = JBCheckBox("状态栏通知")
    private val enablePopupCheckBox = JBCheckBox("弹窗通知")
    
    // 状态栏设置组件
    private val statusBarFormatCombo = ComboBox(SettingsService.StatusBarFormat.values())
    private val showProgressCheckBox = JBCheckBox("在状态栏显示成就进度")
    
    // 主题设置组件
    private val themeColorCombo = ComboBox(SettingsService.ThemeColor.values())
    private val enableGradientCheckBox = JBCheckBox("启用渐变卡片效果")
    private val enableAnimationsCheckBox = JBCheckBox("启用动画效果")
    
    // 成就难度设置组件
    private val difficultyCombo = ComboBox(SettingsService.AchievementDifficulty.values())
    
    // 工作时间设置组件
    private val enableWorkTimeCheckBox = JBCheckBox("启用工作时间提醒")
    private val workStartSpinner = JSpinner(SpinnerNumberModel(9, 0, 23, 1))
    private val workEndSpinner = JSpinner(SpinnerNumberModel(18, 1, 24, 1))
    private val enableWeekendReminderCheckBox = JBCheckBox("周末编码提醒")
    
    // 健康提醒设置组件
    private val enableHealthReminderCheckBox = JBCheckBox("启用健康提醒")
    private val continuousCodingSpinner = JSpinner(SpinnerNumberModel(120, 30, 480, 10)) // 30分钟到8小时
    private val restReminderSpinner = JSpinner(SpinnerNumberModel(60, 15, 240, 5)) // 15分钟到4小时
    
    // 数据隐私设置组件
    private val enableDataCollectionCheckBox = JBCheckBox("启用数据收集（用于改进插件）")
    private val enableUsageAnalyticsCheckBox = JBCheckBox("启用使用分析（匿名）")
    
    override fun getDisplayName(): String = "Code Achievement"
    
    override fun createComponent(): JComponent? {
        if (settingsPanel == null) {
            settingsPanel = createSettingsPanel()
        }
        return settingsPanel
    }
    
    private fun createSettingsPanel(): JPanel {
        val mainPanel = JPanel(BorderLayout())
        mainPanel.preferredSize = Dimension(600, 500)
        
        // 创建滚动面板
        val contentPanel = JPanel()
        contentPanel.layout = BoxLayout(contentPanel, BoxLayout.Y_AXIS)
        contentPanel.border = JBUI.Borders.empty(10)
        
        // 添加各个设置组
        contentPanel.add(createNotificationSettings())
        contentPanel.add(Box.createVerticalStrut(20))
        contentPanel.add(createStatusBarSettings())
        contentPanel.add(Box.createVerticalStrut(20))
        contentPanel.add(createThemeSettings())
        contentPanel.add(Box.createVerticalStrut(20))
        contentPanel.add(createDifficultySettings())
        contentPanel.add(Box.createVerticalStrut(20))
        contentPanel.add(createWorkTimeSettings())
        contentPanel.add(Box.createVerticalStrut(20))
        contentPanel.add(createHealthSettings())
        contentPanel.add(Box.createVerticalStrut(20))
        contentPanel.add(createPrivacySettings())
        
        val scrollPane = JBScrollPane(contentPanel)
        scrollPane.border = BorderFactory.createEmptyBorder()
        mainPanel.add(scrollPane, BorderLayout.CENTER)
        
        return mainPanel
    }
    
    private fun createNotificationSettings(): JPanel {
        val panel = createSectionPanel("🔔 通知设置")
        
        panel.add(enableNotificationsCheckBox)
        panel.add(Box.createVerticalStrut(8))
        
        // 子选项面板
        val subPanel = JPanel()
        subPanel.layout = BoxLayout(subPanel, BoxLayout.Y_AXIS)
        subPanel.border = JBUI.Borders.emptyLeft(20)
        
        subPanel.add(enableSoundCheckBox)
        subPanel.add(enableStatusBarCheckBox)
        subPanel.add(enablePopupCheckBox)
        
        panel.add(subPanel)
        
        // 添加联动逻辑
        enableNotificationsCheckBox.addActionListener {
            val enabled = enableNotificationsCheckBox.isSelected
            enableSoundCheckBox.isEnabled = enabled
            enableStatusBarCheckBox.isEnabled = enabled
            enablePopupCheckBox.isEnabled = enabled
        }
        
        return panel
    }
    
    private fun createStatusBarSettings(): JPanel {
        val panel = createSectionPanel("📊 状态栏设置")
        
        panel.add(createLabeledComponent("显示格式:", statusBarFormatCombo))
        panel.add(Box.createVerticalStrut(8))
        panel.add(showProgressCheckBox)
        
        return panel
    }
    
    private fun createThemeSettings(): JPanel {
        val panel = createSectionPanel("🎨 主题设置")
        
        panel.add(createLabeledComponent("主题色彩:", themeColorCombo))
        panel.add(Box.createVerticalStrut(8))
        panel.add(enableGradientCheckBox)
        panel.add(enableAnimationsCheckBox)
        
        return panel
    }
    
    private fun createDifficultySettings(): JPanel {
        val panel = createSectionPanel("🎯 成就难度")
        
        panel.add(createLabeledComponent("难度等级:", difficultyCombo))
        panel.add(Box.createVerticalStrut(8))
        
        val infoLabel = JBLabel("<html><i>调整成就获取的难易程度。更高难度需要更多代码行数才能解锁成就。</i></html>")
        infoLabel.foreground = UIUtil.getInactiveTextColor()
        panel.add(infoLabel)
        
        return panel
    }
    
    private fun createWorkTimeSettings(): JPanel {
        val panel = createSectionPanel("⏰ 工作时间")
        
        panel.add(enableWorkTimeCheckBox)
        panel.add(Box.createVerticalStrut(8))
        
        val timePanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0))
        timePanel.add(JBLabel("工作时间: "))
        timePanel.add(workStartSpinner)
        timePanel.add(JBLabel(" 点 到 "))
        timePanel.add(workEndSpinner)
        timePanel.add(JBLabel(" 点"))
        
        panel.add(timePanel)
        panel.add(Box.createVerticalStrut(8))
        panel.add(enableWeekendReminderCheckBox)
        
        return panel
    }
    
    private fun createHealthSettings(): JPanel {
        val panel = createSectionPanel("💚 健康提醒")
        
        panel.add(enableHealthReminderCheckBox)
        panel.add(Box.createVerticalStrut(8))
        
        val continuousPanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0))
        continuousPanel.add(JBLabel("连续编码 "))
        continuousPanel.add(continuousCodingSpinner)
        continuousPanel.add(JBLabel(" 分钟后提醒休息"))
        panel.add(continuousPanel)
        
        panel.add(Box.createVerticalStrut(8))
        
        val reminderPanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0))
        reminderPanel.add(JBLabel("每隔 "))
        reminderPanel.add(restReminderSpinner)
        reminderPanel.add(JBLabel(" 分钟提醒护眼"))
        panel.add(reminderPanel)
        
        return panel
    }
    
    private fun createPrivacySettings(): JPanel {
        val panel = createSectionPanel("🔒 隐私设置")
        
        panel.add(enableDataCollectionCheckBox)
        panel.add(Box.createVerticalStrut(8))
        panel.add(enableUsageAnalyticsCheckBox)
        
        val infoLabel = JBLabel("<html><i>数据仅用于改进插件体验，不会包含任何代码内容或敏感信息。</i></html>")
        infoLabel.foreground = UIUtil.getInactiveTextColor()
        panel.add(Box.createVerticalStrut(8))
        panel.add(infoLabel)
        
        return panel
    }
    
    private fun createSectionPanel(title: String): JPanel {
        val panel = JPanel()
        panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS)
        panel.border = JBUI.Borders.compound(
            JBUI.Borders.customLineBottom(JBColor.border()),
            JBUI.Borders.empty(10, 0, 15, 0)
        )
        
        val titleLabel = JBLabel(title)
        titleLabel.font = titleLabel.font.deriveFont(Font.BOLD, 14f)
        titleLabel.foreground = UIUtil.getLabelForeground()
        titleLabel.alignmentX = Component.LEFT_ALIGNMENT
        panel.add(titleLabel)
        
        panel.add(Box.createVerticalStrut(10))
        
        return panel
    }
    
    private fun createLabeledComponent(labelText: String, component: JComponent): JPanel {
        val panel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0))
        panel.add(JBLabel(labelText))
        panel.add(Box.createHorizontalStrut(10))
        panel.add(component)
        return panel
    }
    
    override fun isModified(): Boolean {
        val state = settingsService.state
        
        return state.enableNotifications != enableNotificationsCheckBox.isSelected ||
                state.enableSoundNotifications != enableSoundCheckBox.isSelected ||
                state.enableStatusBarNotifications != enableStatusBarCheckBox.isSelected ||
                state.enablePopupNotifications != enablePopupCheckBox.isSelected ||
                state.statusBarFormat != statusBarFormatCombo.selectedItem ||
                state.showProgressInStatusBar != showProgressCheckBox.isSelected ||
                state.themeColor != themeColorCombo.selectedItem ||
                state.enableGradientCards != enableGradientCheckBox.isSelected ||
                state.enableAnimations != enableAnimationsCheckBox.isSelected ||
                state.achievementDifficulty != difficultyCombo.selectedItem ||
                state.enableWorkTimeReminder != enableWorkTimeCheckBox.isSelected ||
                state.workStartHour != (workStartSpinner.value as Int) ||
                state.workEndHour != (workEndSpinner.value as Int) ||
                state.enableWeekendReminder != enableWeekendReminderCheckBox.isSelected ||
                state.enableHealthReminder != enableHealthReminderCheckBox.isSelected ||
                state.continuousCodingWarningMinutes != (continuousCodingSpinner.value as Int) ||
                state.restReminderIntervalMinutes != (restReminderSpinner.value as Int) ||
                state.enableDataCollection != enableDataCollectionCheckBox.isSelected ||
                state.enableUsageAnalytics != enableUsageAnalyticsCheckBox.isSelected
    }
    
    override fun apply() {
        val state = settingsService.state
        
        state.enableNotifications = enableNotificationsCheckBox.isSelected
        state.enableSoundNotifications = enableSoundCheckBox.isSelected
        state.enableStatusBarNotifications = enableStatusBarCheckBox.isSelected
        state.enablePopupNotifications = enablePopupCheckBox.isSelected
        
        state.statusBarFormat = statusBarFormatCombo.selectedItem as SettingsService.StatusBarFormat
        state.showProgressInStatusBar = showProgressCheckBox.isSelected
        
        state.themeColor = themeColorCombo.selectedItem as SettingsService.ThemeColor
        state.enableGradientCards = enableGradientCheckBox.isSelected
        state.enableAnimations = enableAnimationsCheckBox.isSelected
        
        state.achievementDifficulty = difficultyCombo.selectedItem as SettingsService.AchievementDifficulty
        
        state.enableWorkTimeReminder = enableWorkTimeCheckBox.isSelected
        state.workStartHour = workStartSpinner.value as Int
        state.workEndHour = workEndSpinner.value as Int
        state.enableWeekendReminder = enableWeekendReminderCheckBox.isSelected
        
        state.enableHealthReminder = enableHealthReminderCheckBox.isSelected
        state.continuousCodingWarningMinutes = continuousCodingSpinner.value as Int
        state.restReminderIntervalMinutes = restReminderSpinner.value as Int
        
        state.enableDataCollection = enableDataCollectionCheckBox.isSelected
        state.enableUsageAnalytics = enableUsageAnalyticsCheckBox.isSelected
    }
    
    override fun reset() {
        val state = settingsService.state
        
        enableNotificationsCheckBox.isSelected = state.enableNotifications
        enableSoundCheckBox.isSelected = state.enableSoundNotifications
        enableStatusBarCheckBox.isSelected = state.enableStatusBarNotifications
        enablePopupCheckBox.isSelected = state.enablePopupNotifications
        
        statusBarFormatCombo.selectedItem = state.statusBarFormat
        showProgressCheckBox.isSelected = state.showProgressInStatusBar
        
        themeColorCombo.selectedItem = state.themeColor
        enableGradientCheckBox.isSelected = state.enableGradientCards
        enableAnimationsCheckBox.isSelected = state.enableAnimations
        
        difficultyCombo.selectedItem = state.achievementDifficulty
        
        enableWorkTimeCheckBox.isSelected = state.enableWorkTimeReminder
        workStartSpinner.value = state.workStartHour
        workEndSpinner.value = state.workEndHour
        enableWeekendReminderCheckBox.isSelected = state.enableWeekendReminder
        
        enableHealthReminderCheckBox.isSelected = state.enableHealthReminder
        continuousCodingSpinner.value = state.continuousCodingWarningMinutes
        restReminderSpinner.value = state.restReminderIntervalMinutes
        
        enableDataCollectionCheckBox.isSelected = state.enableDataCollection
        enableUsageAnalyticsCheckBox.isSelected = state.enableUsageAnalytics
        
        // 更新子组件状态
        val notificationsEnabled = enableNotificationsCheckBox.isSelected
        enableSoundCheckBox.isEnabled = notificationsEnabled
        enableStatusBarCheckBox.isEnabled = notificationsEnabled
        enablePopupCheckBox.isEnabled = notificationsEnabled
    }
}
